﻿using UnityEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;

public static class MeshExtensions
{
	public static float CalculateArea( this Mesh mesh )
	{
		float area = 0f;
		for ( int i = 0; i < mesh.subMeshCount; i++ )
		{
			area += CalculateSubArea( mesh, i );
		}
		return area;
	}

	public static float CalculateSubArea( this Mesh mesh, int submesh )
	{
		int[] tri = mesh.GetTriangles( submesh );
		int triCount = tri.Length / 3;
		
		float area = 0f;
		for ( int i = 0; i < triCount; i++ )
		{
			int tIndex = i * 3;
			Vector3 v1 = mesh.vertices[ tri[ tIndex ] ];
			Vector3 v2 = mesh.vertices[ tri[ tIndex + 1 ] ];
			Vector3 v3 = mesh.vertices[ tri[ tIndex + 2 ] ];

			area += Vector3.Dot( v2 - v1, v3 - v1 ) * 0.5f;
		}
		return area;
	}
}